import React, { useEffect, useRef, useState } from 'react';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import diagramXML from './resources/newDiagram.bpmn';

import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';

const BpmnModelerComponent = () => {
  const [modeler, setModeler] = useState(null);
  const ref = useRef(null);

  useEffect(() => {
    const newModeler = new BpmnModeler({
      container: ref.current,
      keyboard: {
        bindTo: window
      }
    });
    
    setModeler(newModeler);
    createNewDiagram(newModeler);

    return () => newModeler.destroy();
  }, []);

  async function createNewDiagram(modeler) {
    try {
      await modeler.importXML(diagramXML);
    } catch (err) {
      console.error('Error rendering', err);
    }
  }

  const handleFileSelect = async (event) => {
    event.preventDefault();
    const file = event.target.files[0];
    if (!file) {
      return;
    }

    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        await modeler.importXML(e.target.result);
      } catch (err) {
        console.error('Error importing XML', err);
      }
    };
    reader.readAsText(file);
  };

  return (
    <div>
      <input type="file" onChange={handleFileSelect} />
      <div ref={ref} style={{ width: '100%', height: '600px' }}></div>
    </div>
  );
};

export default BpmnModelerComponent;